from typing import Dict, Any
import asyncio
from intelli_port.notifications.websocket_hub import hub
from intelli_port.notifications.webhook_client import send_webhooks, add_webhook, add_robot_webhook, send_robot_webhooks


def register_webhook(flight_no: str, url: str, secret: str | None = None) -> Dict[str, Any]:
    ok = add_webhook(flight_no, url, secret)
    return {"ok": ok}


def broadcast(change: Dict[str, Any]) -> Dict[str, Any]:
    fn = str(change.get("flight_no") or "")
    try:
        loop = asyncio.get_event_loop()
    except RuntimeError:
        loop = None
    payload = {"type": "flight_change", **change}
    try:
        if loop and loop.is_running():
            loop.create_task(hub.broadcast(fn, payload))
        else:
            asyncio.run(hub.broadcast(fn, payload))
    except Exception:
        pass
    try:
        send_webhooks(fn, payload)
    except Exception:
        pass
    return {"ok": True}


def broadcast_robot_status(robot_id: int, status: Dict[str, Any]) -> Dict[str, Any]:
    try:
        import asyncio
        loop = asyncio.get_event_loop()
    except RuntimeError:
        loop = None
    topic = f"robot:{int(robot_id)}"
    payload = {"type": "robot_status", **status}
    try:
        if loop and loop.is_running():
            loop.create_task(hub.broadcast(topic, payload))
        else:
            asyncio.run(hub.broadcast(topic, payload))
    except Exception:
        pass
    try:
        send_robot_webhooks(robot_id, payload)
    except Exception:
        pass
    return {"ok": True}


def register_robot_webhook(robot_id: int, url: str, secret: str | None = None) -> Dict[str, Any]:
    ok = add_robot_webhook(robot_id, url, secret)
    return {"ok": ok}